package com.mk.admin.log;


import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.mapper.AdminLogMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.entity.AdminLogEntity;
import com.mk.admin.util.DateTool;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class WriteLogAspect {

    @Autowired
    AdminLogMapper adminLogMapper;

    // com.jankin.inoteadmin.system.annotation.WriteLog 是我定义接口的文件路径
    @Pointcut("@annotation(com.mk.admin.log.WriteLog)")
    public void writeLogAspect() {
    }

    /**
     * 返回通知切面方法
     *
     * @param joinPoint 切点，就是被注解的目标方法
     */
    @Around("writeLogAspect()")
    public Object logPostMapping(ProceedingJoinPoint joinPoint) throws Throwable {
        String userId = null; // 获取操作用户Id
        //我这里用的是SpringSecurity框架，这样获取UserId
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        if (authentication != null) {
        // SecurityUser是自定义的UserDetails类，其中包含了UserId
//            AdminEntity entity = (AdminEntity) authentication.getPrincipal();
//            userId = entity.getId() + "";
//            AdminEntity entity = (AdminEntity) ((Object[])((CglibMethodInvocation)((MethodInvocationProceedingJoinPoint)joinPoint).methodInvocation).arguments)[0];
//            Object[] args = (Object[]) joinPoint.getArgs();
//            if(args.length>0){
//                ToyModelQuery query= (ToyModelQuery) args[0];
//                userId = query.getToyMemberId() + "";
//            }

//        }
        String status = "ERROR";
        String resultStr = "";
        Object result = null;
        long startTime = System.currentTimeMillis();    // 执行前时间
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            resultStr = e.getMessage();
            throw e;
        } finally {
            long finishTime = System.currentTimeMillis();   // 目标方法执行后时间
            if (result instanceof ResultDto) {
                resultStr = JSONObject.toJSONString(result);   // 返回结果字符串
                status = "T".equals(((ResultDto) result).getRetCode()) ? "SUCCESS" : "EXCEPTION";
            }
            // 其他to do ……
            AdminLogEntity sysLog = new AdminLogEntity();

            RequestBaseInfo rbi = RequestContextHolder.getRequestBaseInfo();
            if (rbi != null) {
                sysLog.setOpenId(rbi.getOpenId());
                sysLog.setIp(rbi.getIp());
                sysLog.setUri(rbi.getUri());
                sysLog.setMethodType(rbi.getMethodType());
            }

            sysLog.setMethodName(joinPoint.getSignature().toShortString());
            // 获取注解上的方法描述
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            WriteLog annotation = signature.getMethod().getAnnotation(WriteLog.class);
            sysLog.setMethodDesc(annotation.value());
            String jsonObject = null;
            if (joinPoint.getArgs().length > 0) {
                jsonObject = JSONObject.toJSONString(joinPoint.getArgs()[0]);
            }
            sysLog.setRequestParam(jsonObject);
            sysLog.setStatus(status);
            sysLog.setResult(resultStr);
            sysLog.setCreateTime(DateTool.format());
            sysLog.setExecutionTime(finishTime - startTime);
            adminLogMapper.insert(sysLog);
        }
        return result;
    }

}
